package com.diamond.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.processors.DefaultValueProcessor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;


public abstract class BaseManagerTestCase extends AbstractTransactionalDataSourceSpringContextTests {
	// ~ Static fields/initializers

	protected final Log log = LogFactory.getLog(getClass());
	private static StringBuffer buffer = new StringBuffer();
	private static InputStream is;

	@Override
	protected void onSetUp() {
		SpringContextUtil util = new SpringContextUtil();
		util.setApplicationContext(applicationContext);
	}

	@Override
	protected String[] getConfigLocations() {
		setAutowireMode(AUTOWIRE_BY_NAME);
		setDefaultRollback(false);
		return new String[] { "/Resources/applicationContext*.xml", "/applicationContext.xml" };
		// classpath*:/**/applicationContext.xml has to be used since this file
		// does not
		// exist in AppFuse, but may exist in projects that depend on it
	}

	// ~ Constructors
	// ===========================================================

	public BaseManagerTestCase() {
		// Since a ResourceBundle is not required for each class, just
		// do a simple check to see if one exists
		Class cls = this.getClass();
		String className = cls.getName();
		String classPath = className.replace(".", "/");

		try {
			if (is == null) {
				ClassLoader cl = cls.getClassLoader();
				is = cl.getResourceAsStream(classPath + ".js");
				if (is != null)
					AccessTextFile.readToBuffer(buffer, is);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// ~ Methods
	// ================================================================

	/**
	 * Utility method to populate a javabean-style object with values from a
	 * Properties file
	 * 
	 * @param obj
	 *            the model object to populate
	 * @return Object populated object
	 * @throws Exception
	 *             if BeanUtils fails to copy properly
	 */
	protected List populate(Class cls) {
		// loop through all the beans methods and set its properties from
		// its .properties file
		JsonConfig conf = new JsonConfig();
		conf.registerDefaultValueProcessor(Date.class, new DefaultValueProcessor() {
			public Object getDefaultValue(Class type) {
				return new Date();
			}
		});

		JSONArray arr = JSONArray.fromObject(buffer.toString(), conf);
		return arr.toList(arr, cls);
	}
}
